//
//  BallChatMessageCache.swift
//  BallChat
//
//  Created by mac on 2022/8/16.
//

import UIKit

let ChatCache = PixelWorldChatMessageCache.cache

class PixelWorldChatMessageCache: NSObject, PixelWorldChatToolProtocol {
    
    enum BallChatCacheKey {
        /// 会话列表
        static let conversations = "ballChat_CONVERSATIONS"
    }
    
    static let cache = PixelWorldChatMessageCache()
    
    private var messageKey: String {
        let userId = USEINFOMODEL.id
        return "ballChat_messageHistory_\(userId)"
    }
    
    //TODO: - 保存会话列表
    /// 保存会话列表
    func saveConversation(_ messages: [PixelWorldChatMessageBodyModel], unReadCount: Int  = 0) {
        let messageStr = MMKV.default()?.string(forKey: messageKey + "_conversation")
        var models = messageStr?.kj.modelArray(PixelWorldChatMessageBodyModel.self) ?? []
        models = models.map({ model in
            var messageModel = model
            messageModel.sourceType = PixelWorldChatSourceType(rawValue: model.sourceTypeStr) ?? .none
            messageModel.messageBodyType = PixelWorldChatMessageBodyType(rawValue: model.messageBodyTypeStr) ?? .none
            return messageModel
        })
        messages.forEach { messageModel in
            var itemModel = messageModel
            itemModel.unReadCount += unReadCount
            if let model = models.filter({ $0.easeUserID.lowercased() == messageModel.easeUserID.lowercased() }).first, let index = models.firstIndex(where: { $0.easeUserID.lowercased() == messageModel.easeUserID.lowercased() }) {
                models.remove(at: index)
                itemModel.unReadCount += model.unReadCount
                models.insert(itemModel, at: 0)
            } else {
                models.insert(itemModel, at: 0)
            }
        }
        let jsonData = models.kj.JSONString()
        MMKV.default()?.set(jsonData, forKey: messageKey + "_conversation")
    }
    
    //TODO: - 获取会话列表
    /// 获取会话列表
    func conversationList() -> [PixelWorldChatMessageBodyModel] {
        let messageStr = MMKV.default()?.string(forKey: messageKey + "_conversation")
        let models = messageStr?.kj.modelArray(PixelWorldChatMessageBodyModel.self) ?? []
        var messageModels = [PixelWorldChatMessageBodyModel]()
        models.forEach { model in
            var messageModel = model
            messageModel.lastTime = self.calculateLastMessageTime(serverTime: Int(model.lastTimestamp), isSecond: true)
            messageModels.append(messageModel)
        }
        return messageModels
    }
    
    //TODO: - 保存消息
    /// 保存消息
    func saveMessages(_ messages: [PixelWorldChatMessageBodyModel], unReadCount: Int = 0) {
        // 保存会话列表
        saveConversation(messages, unReadCount: unReadCount)
        guard let message = messages.first else { return }
        let messageKey = messageKey + "_\(message.easeUserID.lowercased())"
        var messageModels = historyMessages(message.easeUserID)
        messageModels.append(contentsOf: messages)
        let jsonData = messageModels.kj.JSONString()
        MMKV.default()?.set(jsonData, forKey: messageKey)
    }
    
    //TODO: - 获取历史消息
    /// 获取历史消息
    func historyMessages(_ easeUserId: String) -> [PixelWorldChatMessageBodyModel] {
        let messageKey = messageKey + "_\(easeUserId.lowercased())"
        let messageStr = MMKV.default()?.string(forKey: messageKey)
        let models = messageStr?.kj.modelArray(PixelWorldChatMessageBodyModel.self) ?? []
        var messageModels = [PixelWorldChatMessageBodyModel]()
        models.forEach { model in
            var messageModel = model
            messageModel.sourceType = PixelWorldChatSourceType(rawValue: model.sourceTypeStr) ?? .none
            messageModel.messageBodyType = PixelWorldChatMessageBodyType(rawValue: model.messageBodyTypeStr) ?? .none
            messageModels.append(messageModel)
        }
        return messageModels
    }
    
    //TODO: - 删除历史记录
    /// 删除历史记录
    func removeConversation(_ easeUserId: String) {
        /// 删除会话列表
        let messageStr = MMKV.default()?.string(forKey: messageKey + "_conversation")
        let models = messageStr?.kj.modelArray(PixelWorldChatMessageBodyModel.self) ?? []
        let messageModels = models.filter({ $0.easeUserID.lowercased() != easeUserId.lowercased() })
        let jsonData = messageModels.kj.JSONString()
        MMKV.default()?.set(jsonData, forKey: messageKey + "_conversation")
        
        // 删除历史记录
        let messageKey = messageKey + "_\(easeUserId.lowercased())"
        MMKV.default()?.removeValue(forKey: messageKey)
    }
    
    //TODO: - 清空未读消息
    /// 清空未读消息
    func cleanUnReadMessages(_ easeUserId: String?) {
        guard let userId = easeUserId, !userId.isEmpty else {
            return
        }
        var messages = conversationList()
        guard let index = messages.firstIndex(where: { $0.easeUserID.lowercased() == userId.lowercased() }) else { return }
        var model = messages[index]
        model.unReadCount = 0
        messages.remove(at: index)
        messages.insert(model, at: index)
        
        let jsonData = messages.kj.JSONString()
        MMKV.default()?.set(jsonData, forKey: messageKey + "_conversation")
    }
    
}
